package com.bingxue.edu.management.education.service;

import cn.hutool.core.bean.BeanUtil;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.framework.mybatis.base.BaseService;
import com.bingxue.edu.management.education.mapper.ClassInfoMapper;
import com.bingxue.edu.management.education.mapper.ClassTypeMapper;
import com.bingxue.edu.management.education.model.entity.ClassType;
import com.bingxue.edu.management.education.model.req.ClassTypeCreateReq;
import com.bingxue.edu.management.education.model.req.ClassTypeUpdateReq;
import com.bingxue.edu.management.education.model.resp.ClassTypeResp;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.bingxue.edu.management.education.model.entity.table.ClassInfoTableDef.CLASS_INFO;

/**
 * 教室类型业务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ClassTypeService extends BaseService<ClassTypeMapper, ClassType> {

    private final ClassInfoMapper classInfoMapper;

    /**
     * 创建教室类型
     */
    public void create(ClassTypeCreateReq req) {
        ClassType classType = new ClassType();
        classType.setName(req.getName());
        classType.setLevel(req.getLevel());
        classType.setStatus(req.getStatus());
        classType.setDescription(req.getDescription());

        this.save(classType);
    }

    /**
     * 根据id删除班级类型
     * 有班级绑定的不可删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<String> ids) {
        QueryWrapper queryWrapper = QueryWrapper.create().where(CLASS_INFO.CLASS_TYPE_ID.in(ids));
        ValidationUtils.throwIf(classInfoMapper.selectCountByQuery(queryWrapper) > 0,"有班级绑定，无法删除");
        this.removeByIds(ids);
    }

    /**
     * 更新类型
     * 不允许修改等级
     */
    public void update(String id, ClassTypeUpdateReq req) {
        ClassType classType = new ClassType();
        classType.setId(id);
        classType.setName(req.getName());
        classType.setStatus(req.getStatus());
        classType.setDescription(req.getDescription());

        this.getMapper().update(classType);
    }


    /**
     * 根据id获取类型详情
     */
    public ClassTypeResp getDetail(String id) {
        ClassType classType = this.getById(id);
        return BeanUtil.copyProperties(classType, ClassTypeResp.class);
    }
}
